import React, { Component } from 'react';
import { grey400 } from 'material-ui/styles/colors';
import CircularProgress from 'material-ui/CircularProgress';

import Masonry from 'react-masonry-component';
import InfiniteScroll from 'react-infinite-scroller';

import CONFIG from '../../config';
import Delete from '../Utils/Delete';
import TweetCard from '../Home/TweetCard';
import {parseJSON,getMethod,postJsonMethod} from '../../redux/Helper';

export default class UserTweets extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      nextPageUrl: null,
      isInfiniteLoading: true,
      openDelete: false,
      deleteId: null,
      dataIndex: null
    }
  }
  
  componentWillMount() {
    this.initFetch();
  }

  /**
   * 初始化时加载数据
   */
  initFetch = () => {
    let url = `${CONFIG.apiHost}/api/tweet/${this.props.userData.id}?token=${this.props.token}`;
    fetch(url, getMethod)
    .then(parseJSON)
    .then(res => {
      if (res.msg.next_page_url) {
        this.setState({isInfiniteLoading: true})
      }else{
        this.setState({isInfiniteLoading: false})
      }
      this.setState({
        data: res.msg.data,
        nextPageUrl: res.msg.next_page_url
      });
    })
  };

  /**
   * 加载时的动画
   */
  elementInfiniteLoad() {
    return (
      <div className="center-block" style={{width: 32}}>
        <CircularProgress 
          size={32} 
          style={{margin: 8}} 
          thickness={3} 
        /> 
      </div>
    );
  }

  /**
   * 滚动加载
   */
  handleInfiniteLoad = () => {
    if (this.state.nextPageUrl) {
      let arr = this.state.data;

      let request = '&token='+this.props.token;
      let url = this.state.nextPageUrl + request;

      fetch(url, getMethod)
      .then(parseJSON)
      .then(res => {
        setTimeout(() => {
          this.setState({
            nextPageUrl: res.msg.next_page_url,
            data: arr.concat(res.msg.data)
          });
        }, 500)
      })
    }else{
      this.setState({isInfiniteLoading: false});
    }
  };

  /**
   * 开启删除页
   */
  handleOpen = () => {
    this.setState({openDelete: true});
  };

  /**
   * 关闭删除页
   */
  handleClose = () => {
    this.setState({openDelete: false});
  };

  /**
   * 将要删除活动信息返回本页
   */
  handleDelete = (v, e, i) => {
    this.setState({deleteId: v, dataIndex: e});
  };

  /**
   * 删除分享
   */
  deleteConfirm = (v, e) => {
    if (v) {
      let url = `${CONFIG.apiHost}/api/tweet/${this.state.deleteId}?token=${this.props.token}`;
      let postData = {user_id: this.props.userId};
      
      let arr = this.state.data;
      arr.splice(this.state.dataIndex, 1);

      fetch(url, postJsonMethod(postData))
      .then(parseJSON)
      .then(res => {
        if (res.status) {
          this.handleClose();
          this.setState({data: arr});
        }
      })
    }
  };

  render() {
    let nullElement = (
      <div style={{width: '100%', textAlign: 'center'}}>
        <p style={{color: grey400}}>暂时还没有活动分享</p>
      </div>
    );

    let elements = this.state.data.map((item, index) => {
      return (
        <TweetCard
          key={index}
          index={index}
          item={item}
          color500={this.props.color500}
          handleOpen={this.handleOpen}
          handleDelete={this.handleDelete}
          isCurrentUser={this.props.isCurrentUser}
        />
      );
    });

  	return (
  	  <div>
        <InfiniteScroll
          pageStart={0}
          loadMore={this.handleInfiniteLoad.bind(this)}
          hasMore={this.state.isInfiniteLoading}
          loader={this.elementInfiniteLoad()}
          initialLoad={false}
          useWindow={true}
          threshold={20}
        >
          <Masonry
            className="center-block"
            style={{width: '100%'}}
            elementType={'div'}
          >
            {this.state.data.length === 0 ? nullElement : elements}
          </Masonry>
        </InfiniteScroll>

        <Delete 
          open={this.state.openDelete}
          handleClose={this.handleClose}
          deleteConfirm={this.deleteConfirm}
        />
      </div>
  	);
  }
};
